package org.useCode.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ThreadPool {
    private static ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("productDetail-pool-%d").build();
    private static ThreadPoolExecutor executorService = new ThreadPoolExecutor(11,
            32, 60,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue(200),
            threadFactory, new ThreadPoolExecutor.AbortPolicy());

    /**
     * 多线程获取，多接口组装数据的方式：
     */
    public void getProductDetailInfo() {
        // 多线程执行数据组装,combination需要组装的个数
        CountDownLatch countDownLatch = new CountDownLatch(combination.size());
        // 组装数据对象
        for (combination combin : combination) {
            try {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //run task combin
                        } catch (Exception e) {
                            LOGGER.error("taskId:{}", request.getTaskId(), e);
                        } finally {
                            countDownLatch.countDown();
                        }
                    }
                });
            } catch (RejectedExecutionException e) {
                LOGGER.error("数据组装线程池队列已满，需要调整队列大小");
            }
        }
        
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            LOGGER.error("组装数据时countDownLatch等待时中断异常");
        }
        return null;
    }

}
